package com.seeyon.apps.kkSample.listener;

import com.seeyon.apps.collaboration.api.CollaborationApi;
import com.seeyon.apps.collaboration.event.*;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.service.CAP4FormCacheManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.affair.manager.AffairManager;
import com.seeyon.ctp.common.content.affair.constants.StateEnum;
import com.seeyon.ctp.common.content.comment.Comment;
import com.seeyon.ctp.common.content.comment.CommentManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.po.affair.CtpAffair;
import com.seeyon.ctp.common.po.template.CtpTemplate;
import com.seeyon.ctp.common.template.manager.TemplateManager;
import com.seeyon.ctp.form.modules.event.FormDataAfterSubmitEvent;
import com.seeyon.ctp.form.util.Enums;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.annotation.Inject;
import com.seeyon.ctp.util.annotation.ListenEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.*;

public class CommonListener {
    private final static Log log = LogFactory.getLog(CommonListener.class);//记录日志
    public static String templeteCodes = AppContext.getSystemProperty("kkSample.templeteCodes");
    private final CAP4FormCacheManager cap4FormCacheManager = (CAP4FormCacheManager) AppContext.getBean("cap4FormCacheManager");
    private final TemplateManager templateManager = (TemplateManager) AppContext.getBean("templateManager");
    private final CollaborationApi collaborationApi = (CollaborationApi) AppContext.getBean("collaborationApi");
    //    private final ColManager colManager = (ColManager) AppContext.getBean("colManager");
    @Inject
    private CommentManager commentManager;

    @Inject
    private AffairManager affairManager;


    /**
     * 流程处理事件
     *
     * @param event
     */
    @ListenEvent(event = CollaborationProcessEvent.class, async = true)
    public void onCollaborationProcessEvent(CollaborationProcessEvent event) {
        log.info("----------------------------[CollaborationProcessEvent]  开始处理 - summaryId: {}" + event.getSummaryId());
        try {
            String code = isRightFlow(event.getSummaryId());
            if (Strings.isNotEmpty(code)) {
                boolean flag = true;//发送
                Comment comment = event.getComment();
                log.info("----------------------------[CollaborationProcessEvent]  评论内容: {}" + comment.getContent());
                log.info("----------------------------[CollaborationProcessEvent]  评论扩展属性4: {}" + comment.getExtAtt4());

                if ("haveRead".equals(comment.getExtAtt4())) {
                    log.info("----------------------------[onCollaborationProcessEvent]   - haveRead:");
                } else if ("agree".equals(comment.getExtAtt4())) {
                    log.info("----------------------------[onCollaborationProcessEvent]   - agree:");
                } else if ("disagree".equals(comment.getExtAtt4())) {
                    log.info("----------------------------[onCollaborationProcessEvent]   - disagree:");
                } else {
                    log.info("----------------------------[onCollaborationProcessEvent]   - 未知操作:");
                    return;
                }

                String Contentone = comment.getContent();
                // 处理无手写意见的逻辑
                if ("agree".equals(comment.getExtAtt4()) && (Contentone == null || Contentone.trim().isEmpty())) {
                    log.info("----------------------------[onCollaborationProcessEvent]   - 无手写意见，跳过处理");
                    return;
                }

                log.info("----------------------------[onCollaborationProcessEvent] comment: {}" + comment);
                List<StateEnum> stateEnums = new ArrayList<>();
                stateEnums.add(StateEnum.col_done);
                stateEnums.add(StateEnum.col_sent);
                List<CtpAffair> affairs = affairManager.getAffairs(event.getSummaryId(), stateEnums);
                CtpAffair affair = event.getAffair();
                log.info("----------------------------[onCollaborationProcessEvent] 获取到的事项列表: {}affair" + affair);
                log.info("----------------------------[onCollaborationProcessEvent] 获取到的事项列表: {}" + affairs);
                for (CtpAffair ctpAffair : affairs) {
                    log.info("----------------------------[onCollaborationProcessEvent] 发送邮件给事项ID: {}" + ctpAffair.getId());
                    log.info("----------------------------[onCollaborationProcessEvent] 发送邮件给事项ID: {}" + ctpAffair.getId());
                    if (!Objects.equals(affair.getId(), ctpAffair.getId())) {
                        log.info("----------------------------[onCollaborationProcessEvent] 发送邮件给事项ID: {}" + ctpAffair.getId());
                    }

                }
            } else {
                log.info("----------------------------[onCollaborationProcessEvent] 流程不符合条件，跳过处理");
            }
        } catch (Exception e) {
            log.error("----------------------------[onCollaborationProcessEvent] 处理过程中发生异常 - summaryId: {}" + event.getSummaryId(), e);
        } finally {
            log.info("----------------------------[onCollaborationProcessEvent]  结束处理 - summaryId: {}" + event.getSummaryId());
        }
    }


    /**
     * 流程回退事件
     *
     * @param event
     */
    @ListenEvent(event = CollaborationStepBackEvent.class, async = true)
    public void onCollaborationStepBackEvent(CollaborationStepBackEvent event) {
        log.info("----------------------------[CollaborationStepBackEvent]  开始处理 - summaryId: {}" + event.getSummaryId());
        try {
            String code = isRightFlow(event.getSummaryId());
            if (Strings.isNotEmpty(code)) {
                CtpAffair affair = event.getAffair();
                ColSummary colSummary = this.collaborationApi.getColSummary(event.getSummaryId());
                log.info("----------------------------[CollaborationStepBackEvent] 回退事件 - 事项: {}" + affair);
                log.info("----------------------------[CollaborationStepBackEvent] 回退事件 - 协同摘要: {}" + colSummary);
            } else {
                log.info("----------------------------[CollaborationStepBackEvent] 流程不符合条件，跳过处理");
            }
        } catch (Exception e) {
            log.error("----------------------------[CollaborationStepBackEvent] 处理过程中发生异常 - summaryId: {}" + event.getSummaryId(), e);
        } finally {
            log.info("----------------------------[CollaborationStepBackEvent] onCollaborationStepBackEvent 结束处理 - summaryId: {}" + event.getSummaryId());
        }
    }

    /**
     * 指定回退事件
     *
     * @param event
     */
    @ListenEvent(event = CollaborationAppointStepBackEvent.class, async = true)
    public void onCollaborationAppointStepBackEvent(CollaborationAppointStepBackEvent event) {
        log.info("----------------------------[onCollaborationAppointStepBackEvent]  开始处理 - summaryId: {}" + event.getSummaryId());
        try {
            String code = isRightFlow(event.getSummaryId());
            if (Strings.isNotEmpty(code)) {
                CtpAffair affair = event.getCurrentAffair();
                ColSummary colSummary = this.collaborationApi.getColSummary(event.getSummaryId());
                log.info("----------------------------[onCollaborationAppointStepBackEvent] 指定回退事件 - 事项: {}" + affair);
                log.info("----------------------------[onCollaborationAppointStepBackEvent] 指定回退事件 - 协同摘要: {}" + colSummary);
            } else {
                log.info("----------------------------[onCollaborationAppointStepBackEvent] 流程不符合条件，跳过处理");
            }
        } catch (Exception e) {
            log.error("----------------------------[onCollaborationAppointStepBackEvent] 处理过程中发生异常 - summaryId: {}" + event.getSummaryId(), e);
        } finally {
            log.info("----------------------------[onCollaborationAppointStepBackEvent]  结束处理 - summaryId: {}" + event.getSummaryId());
        }
    }

    /**
     * 协同结束事件（不含终止）
     */
    @ListenEvent(event = CollaborationFinishEvent.class, async = true)
    public void CollaborationFinishEvent(CollaborationFinishEvent event) {
        try {
            String code = isRightFlow(event.getSummaryId());
            if (Strings.isNotEmpty(code)) {
                Long summaryId = event.getSummaryId();
                CtpAffair affair = event.getAffair();
                ColSummary colSummary = this.collaborationApi.getColSummary(summaryId);
                log.info("----------------------------[CollaborationFinishEvent] 协同结束事件 - 事项: {}" + affair);
                log.info("----------------------------[CollaborationFinishEvent] 协同结束事件 - 协同摘要: {}" + colSummary);
            } else {
                log.info("----------------------------[CollaborationFinishEvent] 流程不符合条件，跳过处理");
            }
        } catch (Exception e) {
            log.error("----------------------------[CollaborationFinishEvent] 处理过程中发生异常 - summaryId: {}" + event.getSummaryId(), e);
        } finally {
            log.info("----------------------------[CollaborationFinishEvent]  结束处理 - summaryId: {}" + event.getSummaryId());
        }
    }

    private String isRightFlow(Long summaryId) {
        log.info("----------------------------[CollaborationFinishEvent] isRightFlow 开始处理 - summaryId: {}" + summaryId);
        String code = getTempalteCode(summaryId);
        // 使用 split() 方法按分号分割字符串
        String[] array = templeteCodes.split(";");
        // 将数组转换为 List
        List<String> codes = Arrays.asList(array);
        if (Strings.isNotEmpty(code) && (codes.contains(code))) {
            log.info("----------------------------[CollaborationFinishEvent] isRightFlow 结束处理 - 返回值: {}" + code);
            return code;
        } else {
            log.info("----------------------------[CollaborationFinishEvent] isRightFlow 结束处理 - 返回值: 无匹配模板");
            return "";
        }
    }

    private String getTempalteCode(Long summaryId) {
        log.info("----------------------------[CollaborationFinishEvent] getTempalteCode 开始处理 - summaryId: {}" + summaryId);
        try {
            ColSummary summary = collaborationApi.getColSummary(summaryId);
            if (null != summary) {
                log.info("----------------------------[CollaborationFinishEvent] getTempalteCode 开始处理 - summaryId: {}" + summary.getSubject());
                CtpTemplate template = templateManager.getCtpTemplate(summary.getTempleteId());
                if (null != template) {
                    log.info("----------------------------[CollaborationFinishEvent] getTempalteCode 结束处理 - 返回值: {}" + template.getTempleteNumber());
                    return template.getTempleteNumber();
                } else {
                    log.info("----------------------------[CollaborationFinishEvent] getTempalteCode 结束处理 - 模板为空");
                }
            } else {
                log.info("----------------------------[CollaborationFinishEvent] getTempalteCode 结束处理 - 协同摘要为空");
            }
        } catch (BusinessException e) {
            log.error("----------------------------[CollaborationFinishEvent] getTempalteCode 处理过程中发生异常 - summaryId: {}" + summaryId, e);
        }
        log.info("----------------------------[CollaborationFinishEvent] getTempalteCode 结束处理 - 返回值: 无模板编号");
        return "";
    }
    /**
     * 流程撤销事件
     *
     * @param event
     */
    @ListenEvent(event = CollaborationCancelEvent.class, async = true)
    public void onCollaborationCancelEvent(CollaborationCancelEvent event) {
        String code = isRightFlow(event.getSummaryId());
        if (Strings.isNotEmpty(code)) {
            Map<String, Object> map = new HashMap<String, Object>();
        }
    }

    /**
     * 流程终止操作
     *
     * @param event
     */
    @ListenEvent(event = CollaborationStopEvent.class, async = true)
    public void onCollaborationStepBackEvent(CollaborationStopEvent event) {
        String code = isRightFlow(event.getSummaryId());
        if (Strings.isNotEmpty(code)) {
            Map<String, Object> map = new HashMap<String, Object>();

        }
    }
    /**
     * 流程取回监听
     *
     * @param event
     */
    @ListenEvent(event = CollaborationTakeBackEvent.class, async = true)
    public void onCollaborationTakeBackEvent(CollaborationTakeBackEvent event) {
        String code = isRightFlow(event.getSummaryId());
        if (Strings.isNotEmpty(code)) {
            Map<String, Object> map = new HashMap<String, Object>();

        }
    }

    /**
     * 监听对应模板编号台账的数据变化
     *
     * @param event
     * @throws BusinessException
     */
    @ListenEvent(event = FormDataAfterSubmitEvent.class, async = true)
    public void onFormDataAfterSubmitEvent(FormDataAfterSubmitEvent event) throws BusinessException {
        log.info("[LOGGER]监听CAP4台账数据变化-AfterSubmitEvent-START");
        Long formId = 0L;
        String templateCode = "";
        if (event.getSource() != null && event.getSource() instanceof FormDataMasterBean) {
            FormDataMasterBean srcData = (FormDataMasterBean) event.getSource();
            if (srcData.getFormTable() != null && srcData.getFormTable().getFormId() != null) {
                List<Map> ls = null;
                formId = srcData.getFormTable().getFormId();
                FormBean formBean = cap4FormCacheManager.getForm(srcData.getFormTable().getFormId());
                int formType = formBean.getFormType();
                //判断是否为台账
                Enums.FormType formTypeEnum = Enums.FormType.getEnumByKey(formBean.getFormType());
                if (formTypeEnum.isFlowForm()) {
                    //台账模板编号
                    templateCode = formBean.getBind().getFormCode();
                    //查询是否为合同信息台账
//                    String htxxTemplateCode = CommonUtil.queryDevValueByKey("合同信息台账模板编号");
//                    if (Strings.equals(templateCode, htxxTemplateCode)) {
//                        //调动实际的任务
//                        //合同信息台账数据变化需要更新同步到集团12个台账中START
//                        syncFormManager.syncForm(srcData);
//                        //合同信息台账数据变化需要更新同步到集团12个台账中END
//                    }
                }


            }

        }

        log.info("[LOGGER]监听CAP4台账数据变化-AfterSubmitEvent-END");
    }

    /**
     * 流程发起事件
     *
     * @param event
     */
    @ListenEvent(event = CollaborationStartEvent.class, async = true)
    public void onCollaborationStartEvent(CollaborationStartEvent event) {
        String code = isRightFlow(event.getSummaryId());
        if (Strings.isNotEmpty(code)) {
            Map<String, Object> map = new HashMap<>();
            map.put("type" , 0);
            map.put("code" , code);
            map.put("summaryId" , event.getSummaryId());
            // flowOperateBatchTask.addTask(map);
        }

    }


}


